<template>
  <div class="expert-detail-page min-h-screen  pb-16 max-w-[1600px] mx-auto">
    <div class="mx-auto">
      <!-- <div class="max-w-4xl mx-auto"> -->
      <!-- 顶部卡片 -->
      <div class="relative bg-gradient-to-r from-[#e6f0fa] to-[#fafdff] rounded-3xl shadow-xl p-10 flex gap-10 items-center mt-12 mb-8">
        <el-button class="!absolute left-6 top-6 z-10" @click="$router.back()" type="text" size="large">
          <el-icon><Back /></el-icon> 返回
        </el-button>
        
        <!-- 加载中状态 -->
        <el-skeleton v-if="loading" :rows="4" animated />
        
        <!-- 加载完成后显示内容 -->
        <template v-else>
          <div class="avatar-ring-big shrink-0">
            <img
      :src="expert.avatar || defaultAvatar"
      alt=""
      class="rounded-full  object-cover"
      :style="{ width: ' 112px', height:  '112px' }" />
            <!-- <UserAvatar :avatar="expert.avatar || defaultAvatar" :size="112" :noDropdown="false" /> -->
          </div>
          <div class="flex-1 min-w-0">
            <div class="flex items-center gap-4 mb-2">
              <span class="text-3xl font-extrabold text-blue-900">{{ expert.name }}</span>
              <el-tag v-if="expert.honor" type="primary" effect="dark" class="ml-2">{{ expert.honor }}</el-tag>
            </div>
            <div class="flex flex-wrap gap-2 mb-2">
              <el-tag
                v-for="(tag, idx) in displayFields"
                :key="tag"
                :type="tagColor(tag)"
                size="small"
                class="font-medium"
              >{{ tag }}</el-tag>
              <el-tooltip v-if="hiddenFields.length" placement="top">
                <template #content>
                  <div class="flex flex-wrap gap-1 max-w-xs">
                    <el-tag
                      v-for="tag in allFields"
                      :key="tag + '-all'"
                      :type="tagColor(tag)"
                      size="small"
                      class="font-medium mb-1"
                    >{{ tag }}</el-tag>
                  </div>
                </template>
                <el-tag size="small" class="bg-blue-50 text-blue-600 font-medium">+{{ hiddenFields.length }}</el-tag>
              </el-tooltip>
            </div>
            <div class="text-slate-500 mb-1">{{ expert.orgName }}</div>
            <div class="text-slate-400 text-sm mb-1">联系方式：{{ expert.contact || '—' }}</div>
            <div class="text-slate-400 text-sm mb-1">邮箱：{{ expert.email || '—' }}</div>
            <div class="flex items-center justify-between mt-4">
              <div class="flex gap-8 text-base font-semibold">
                <span><el-icon><ChatDotRound /></el-icon> 答复 {{ expert.ext?.answerCount || 0 }}</span>
                <span><el-icon><StarFilled /></el-icon> 最佳率 {{ expert.ext?.bestAnswerRate || 0 }}%</span>
              </div>
              <el-button
                type="primary"
                size="large"
                class="ask-question-btn"
                @click="handleAskQuestion"
              >
                <el-icon class="mr-2"><ChatDotRound /></el-icon>
                向TA提问
              </el-button>
            </div>
          </div>
        </template>
      </div>
      <!-- 专家简介 -->
      <div class="bg-white rounded-2xl shadow p-8 mb-8">
        <div class="font-bold text-lg mb-2">专家简介</div>
        <div v-if="loading" class="w-full">
          <el-skeleton :rows="3" animated />
        </div>
        <div v-else class="text-slate-700 leading-relaxed">
          <div class="mb-4">{{ expert.introduction || '暂无简介' }}</div>
          <div class="mb-4">
            <span class="font-medium">研究成果：</span>
            {{ expert.research || '暂无研究成果' }}
          </div>
          <div class="mb-4">
            <span class="font-medium">个人履历：</span>
            {{ expert.resume || '暂无个人履历' }}
          </div>
        </div>
      </div>
      <!-- Tab区块 -->
      <div class="bg-white rounded-2xl shadow p-0 mb-8">
        <el-tabs v-model="activeTab" class="expert-tabs" stretch>
          <el-tab-pane label="提问" name="article">
            <ExpertTabList :list="pagedArticles" :type="'question'" :total="articles.total" />
          </el-tab-pane>
          <el-tab-pane label="回答" name="question">
            <ExpertTabList :list="pagedQuestions" :type="'answer'" :total="questions.total" />
          </el-tab-pane>
          <el-tab-pane label="音视频答疑" name="reply">
            <ExpertTabList :list="pagedReplies" :type="'reply'" :total="replies.total" />
          </el-tab-pane>
          <el-tab-pane label="文字答疑" name="imageText">
            <ExpertTabList :list="pagedImageTexts" :type="'imageText'" :total="imageTexts.total" />
          </el-tab-pane>
        </el-tabs>
        <!-- 统一的分页组件 -->
        <div class="px-8 pb-8">
          <el-pagination
            v-if="getCurrentTotal > pageSize"
            background
            layout="prev, pager, next"
            :total="getCurrentTotal"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handlePageChange"
            class="custom-pagination mt-4"
          />
        </div>
      </div>
    </div>
    <QuestionDialog v-model:visible="showQuestionDialog" :uid="expert.uid" :type="1" @success="handleQuestionSuccess" />

  </div>
</template>
<script setup>
import { useRoute, useRouter } from 'vue-router'
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import UserAvatar from '@/components/UserAvatar/UserAvatar.vue'
import { Back, ChatDotRound, StarFilled } from '@element-plus/icons-vue'
import ExpertTabList from './components/ExpertTabList.vue'
import QuestionDialog from '@/views/Submit/components/QuestionDialog.vue'

import { getExpertInfo } from '@/axios/api/expert'
import { get } from '@/axios/utils/request'


import { useGlobalStore } from '@/stores/globalStore'
const globalStore = useGlobalStore()

const route = useRoute()
const router = useRouter()
const defaultAvatar = 'https://img1.baidu.com/it/u=1618033988,3141592653&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200'
// Tab相关
const activeTab = ref('article')
const articles = ref({ list: [], total: 0 })
const questions = ref({ list: [], total: 0 })
const replies = ref({ list: [], total: 0 })
const imageTexts = ref({ list: [], total: 0 })

const expert = ref({})
const loading = ref(false)

const showQuestionDialog = ref(false)
const handleQuestionSuccess = () => {
  showQuestionDialog.value = false
  ElMessage.success('提问成功！')
  router.back()
  // fetchList(getCurrentType.value, 1)
}

const handleAskQuestion = () => {
  showQuestionDialog.value = true
}

//头部按钮点击
watch(
  () => globalStore.isShowQuestionDialog,
  (val) => {
    if (val) {
      showQuestionDialog.value = true
    }
  }
)




// 分页相关
const pageSize = 10
const currentPage = ref(1)

// 获取当前激活tab的总数
const getCurrentTotal = computed(() => {
  switch(activeTab.value) {
    case 'question':
      return articles.value.total
    case 'answer':
      return questions.value.total
    case 'reply':
      return replies.value.total
    case 'imageText':
      return imageTexts.value.total
    default:
      return 0
  }
})

// 获取当前激活tab对应的type
const getCurrentType = computed(() => {
  switch(activeTab.value) {
    case 'article':
      return 1
    case 'question':
      return 2
    case 'reply':
      return 3
    case 'imageText':
      return 4
    default:
      return 1
  }
})

// 处理分页变化
function handlePageChange(page) {
  currentPage.value = page
  fetchList(getCurrentType.value, page)
}

// 监听tab切换
watch(activeTab, () => {
  currentPage.value = 1
  fetchList(getCurrentType.value, 1)
})

// 获取列表数据
const fetchList = async (type, page) => {
  try {
    const res = await get('/expert/profile/list', {
      page,
      size: pageSize,
      type,
      uid: expert.value.uid,
      isSelf: false
    })
    if (res.code === 0) {
      const { list, totalCount } = res.data
      switch(type) {
        case 1:
          articles.value = { list, total: totalCount }
          break
        case 2:
          questions.value = { list, total: totalCount }
          break
        case 3:
          replies.value = { list, total: totalCount }
          break
        case 4:
          imageTexts.value = { list, total: totalCount }
          break
      }
    }
  } catch (error) {
    console.error('获取列表数据失败:', error)
  }
}

// 詳情
const fetchExpertInfo = async () => {
  try {
    loading.value = true
    const res = await getExpertInfo(route.params.id)
    if (res.code === 0) {
      expert.value = res.data
       // 初始加载当前tab的第一页数据
    fetchList(getCurrentType.value, 1)
    }
  } catch (error) {
    console.error('获取专家详情失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchExpertInfo()
 
})

const allFields = computed(() => expert.value.specialtyTagNames || [])
const displayFields = computed(() => allFields.value.slice(0, 2))
const hiddenFields = computed(() => allFields.value.length > 2 ? allFields.value.slice(2) : [])
const tagColorMap = ['success', 'info', 'warning', 'danger', 'primary']
function tagColor(tag) {
  let hash = 0
  for (let i = 0; i < tag.length; i++) hash += tag.charCodeAt(i)
  return tagColorMap[hash % tagColorMap.length]
}

// 计算分页数据
const pagedArticles = computed(() => articles.value.list)
const pagedQuestions = computed(() => questions.value.list)
const pagedReplies = computed(() => replies.value.list)
const pagedImageTexts = computed(() => imageTexts.value.list)

</script>
<style scoped>
.avatar-ring-big {
  border-radius: 50%;
  padding: 8px;
  background: linear-gradient(135deg, #4f9cff 0%, #a3c8fa 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 24px 0 rgba(56,112,255,0.10);
}
.expert-tabs {
  --el-tabs-header-height: 56px;
  --el-tabs-header-bg-color: #fafdff;
  --el-tabs-active-color: #1765ad;
  --el-tabs-header-font-size: 18px;
  --el-tabs-header-font-weight: 600;
  --el-tabs-header-border-radius: 2rem 2rem 0 0;
  --el-tabs-header-box-shadow: 0 2px 12px 0 rgba(56,112,255,0.06);
}
.custom-pagination :deep(.el-pager li) {
  border-radius: 1.5rem;
  margin: 0 4px;
  font-size: 18px;
  min-width: 40px;
  height: 40px;
  line-height: 40px;
  color: #1765ad;
  transition: background 0.2s, color 0.2s;
}
.custom-pagination :deep(.el-pager li.active) {
  background: linear-gradient(90deg, #4f9cff 0%, #1765ad 100%);
  color: #fff;
  font-weight: bold;
  box-shadow: 0 2px 8px 0 rgba(56,112,255,0.10);
}

.ask-question-btn {
  background: linear-gradient(135deg, #4f9cff 0%, #1765ad 100%);
  border: none;
  border-radius: 12px;
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 600;
  color: #fff;
  box-shadow: 0 4px 16px 0 rgba(79, 156, 255, 0.3);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.ask-question-btn:hover {
  background: linear-gradient(135deg, #1765ad 0%, #4f9cff 100%);
  box-shadow: 0 6px 20px 0 rgba(79, 156, 255, 0.4);
  transform: translateY(-2px);
}

.ask-question-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 8px 0 rgba(79, 156, 255, 0.3);
}

.ask-question-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s;
}

.ask-question-btn:hover::before {
  left: 100%;
}
</style>
 